﻿using Game.Facade;
using Game.Utils.Cache;
using System;
using System.Collections.Generic;
using System.Drawing;
using System.Drawing.Drawing2D;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

namespace Game.Web
{
    public partial class ValidateImage2 : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            CreateCheckCodeImage(GenerateCheckCode());
        }

        public static string[] GenerateCheckCode()
        {
            int intFirst, intSec, intTemp;

            string[] checkCode = new string[4];

            System.Random random = new Random();

            intFirst = random.Next(1, 10);
            intSec = random.Next(1, 10);
            switch (random.Next(0, 3).ToString())
            {
                case "2":
                    if (intFirst < intSec)
                    {
                        intTemp = intFirst;
                        intFirst = intSec;
                        intSec = intTemp;
                    }
                    checkCode[0] = intFirst.ToString();
                    checkCode[1] = "-";
                    checkCode[2] = intSec.ToString();
                    checkCode[3] = "=";
                    SaveCheckCode(AppConfig.VerifyCodeKey, intFirst - intSec);
                    break;
                case "1":
                    checkCode[0] = intFirst.ToString();
                    checkCode[1] = "x";
                    checkCode[2] = intSec.ToString();
                    checkCode[3] = "=";
                    SaveCheckCode(AppConfig.VerifyCodeKey, intFirst * intSec);
                    break;
                default:
                    checkCode[0] = intFirst.ToString();
                    checkCode[1] = "+";
                    checkCode[2] = intSec.ToString();
                    checkCode[3] = "=";
                    SaveCheckCode(AppConfig.VerifyCodeKey, intFirst + intSec);
                    break;
            }
            return checkCode;
        }

        #region 产生波形滤镜效果
        private const double PI = 3.1415926535897932384626433832795;
        private const double PI2 = 6.283185307179586476925286766559;
        private System.Drawing.Bitmap TwistImage(Bitmap srcBmp, bool bXDir, double dMultValue, double dPhase)
        {
            System.Drawing.Bitmap destBmp = new Bitmap(srcBmp.Width, srcBmp.Height);

            // 将位图背景填充为白色  
            System.Drawing.Graphics graph = System.Drawing.Graphics.FromImage(destBmp);
            graph.FillRectangle(new SolidBrush(System.Drawing.Color.White), 0, 0, destBmp.Width, destBmp.Height);
            graph.Dispose();

            double dBaseAxisLen = bXDir ? (double)destBmp.Height : (double)destBmp.Width;

            for (int i = 0; i < destBmp.Width; i++)
            {
                for (int j = 0; j < destBmp.Height; j++)
                {
                    double dx = 0;
                    dx = bXDir ? (PI2 * (double)j) / dBaseAxisLen : (PI2 * (double)i) / dBaseAxisLen;
                    dx += dPhase;
                    double dy = Math.Sin(dx);

                    // 取得当前点的颜色  
                    int nOldX = 0, nOldY = 0;
                    nOldX = bXDir ? i + (int)(dy * dMultValue) : i;
                    nOldY = bXDir ? j : j + (int)(dy * dMultValue);

                    System.Drawing.Color color = srcBmp.GetPixel(i, j);
                    if (nOldX >= 0 && nOldX < destBmp.Width
                     && nOldY >= 0 && nOldY < destBmp.Height)
                    {
                        destBmp.SetPixel(nOldX, nOldY, color);
                    }
                }
            }

            return destBmp;
        }
        #endregion
        public static void CreateCheckCodeImage(string[] checkCode)
        {
            if (checkCode == null || checkCode.Length !=4)
                return;

            System.Drawing.Bitmap image = new System.Drawing.Bitmap((int)Math.Ceiling((checkCode.Length * 20.0)), 25);
            Graphics g = Graphics.FromImage(image);

            try
            {
                //生成随机生成器  
                Random random = new Random();

                //清空图片背景色  
                g.Clear(Color.White);

                Color[] colors = { Color.Tomato,Color.Blue,Color.Brown,Color.Black,Color.Green,Color.Wheat,Color.DarkRed };

                //画图片的背景噪音线  
                for (int i = 0; i < 18; i++)
                {
                    int x1 = random.Next(image.Width);
                    int x2 = random.Next(image.Width);
                    int y1 = random.Next(image.Height);
                    int y2 = random.Next(image.Height);

                    g.DrawLine(new Pen(Color.FromArgb(random.Next())), x1, y1, x2, y2);
                }

                Font[] fonts =
                    {
                        new Font("Verdana", 16, (FontStyle.Bold)),
                        new Font("Microsoft Sans Serif", 16, (FontStyle.Bold)),
                        new Font("Comic Sans MS", 16, (FontStyle.Bold)),
                        new Font("FangSong", 16, (FontStyle.Bold)),
                        new Font("KaiTi", 16, (FontStyle.Bold)),
                        new Font("Arial", 16, (FontStyle.Bold))
                    };
                LinearGradientBrush brush = null;
                for(int i = 0; i < checkCode.Length; i++)
                {
                    if(i == 1 || i == 3)
                    {
                        brush = new LinearGradientBrush(new Rectangle(0, 0, image.Width, image.Height), Color.Blue, Color.DarkRed, 1.2f, true);
                        g.DrawString(checkCode[i], fonts[1], brush, (i * random.Next(15, 21) + 1), 1);
                    }
                    else
                    {
                        brush = new LinearGradientBrush(new Rectangle(0, 0, image.Width, image.Height), colors[random.Next(3)], colors[random.Next(3, 6)], 1.2f, true);
                        g.DrawString(checkCode[i], fonts[random.Next(6)], brush, (i * random.Next(15, 21) + 1), 1);
                    }
                }
                
                //画图片的前景噪音点  
                for (int i = 0; i < 180; i++)
                {
                    int x = random.Next(image.Width);
                    int y = random.Next(image.Height);

                    image.SetPixel(x, y, Color.FromArgb(random.Next()));
                }  

                //画图片的边框线  
                g.DrawRectangle(new Pen(Color.Silver), 0, 0, image.Width - 1, image.Height - 1);

                System.IO.MemoryStream ms = new System.IO.MemoryStream();
                image.Save(ms, System.Drawing.Imaging.ImageFormat.Gif);
                System.Web.HttpContext.Current.Response.ClearContent();
                System.Web.HttpContext.Current.Response.ContentType = "image/Gif";
                System.Web.HttpContext.Current.Response.BinaryWrite(ms.ToArray());
            }
            finally
            {
                g.Dispose();
                image.Dispose();
            }
        }

        /// <summary>
        /// 缓存验证码
        /// </summary>
        /// <param name="key">验证码键值</param>
        /// <param name="value">验证码值</param>
        private static void SaveCheckCode(string key, object value)
        {
            //清空验证码缓存
            if (null != WHCache.Default.Get<SessionCache>(AppConfig.VerifyCodeKey))
            {
                WHCache.Default.Delete<SessionCache>(AppConfig.VerifyCodeKey);
            }
            if (null != WHCache.Default.Get<CookiesCache>(AppConfig.VerifyCodeKey))
            {
                WHCache.Default.Delete<CookiesCache>(AppConfig.VerifyCodeKey);
            }

            //缓存新验证码
            WHCache.Default.Save<SessionCache>(key, value);
            WHCache.Default.Save<CookiesCache>(key, value);
        }
    }
}